﻿<%@ include file="/common/validate.jsp"%>
<%@ page import="
org.apache.http.HttpResponse,org.apache.http.client.methods.HttpPost,org.apache.http.entity.StringEntity,org.apache.http.impl.client.DefaultHttpClient,org.apache.http.util.EntityUtils"%>
<%@ page import="com.alibaba.fastjson.TypeReference" %>
<%!
	// 获取环信token
	// access_token存储  type  0是企业号， 1是公众号，  2是环信
	public static Message createToken(Input input) {
		String HUANXIN_TOKEN = "https://a1.easemob.com/" + input.getDesc("application").replace("#", "/") + "/token";
		Integer hospital = input.getInt("hospital");
		String accessToken = input.getDesc("access_token");
		Integer type = input.getInt("type", 0); // 默认企业号
		Integer expireIn = 7000;
		String hql = "from access_token where hospital = " + hospital + " and type=" + type + " and status = " + STATUS_ENABLE + " order by create_time desc";
		List list = QBuilder.db("basedb").queryHql(hql);
		if (list.size() != 0) {
			return refreshToken(input);
		}
		if (type == 2) {
			expireIn = 5180000;// 环信默认7天有效期
			List<Hospital> hList = QBuilder.db("basedb").queryHql("from Hospital where hospital=" + hospital);
			if (hList.size() == 0) {
				return new Message(1999, "参数hospital不存在");
			}
			Map jsonMap = hList.get(0).getJson();
			if (jsonMap.get("grant_type") == null) {
				return new Message(2001, "没有该医院的环信账号");
			}
			Map<String, String> param = new HashMap<String, String>();
			param.put("grant_type", jsonMap.get("grant_type") + "");
			param.put("client_id", jsonMap.get("client_id") + "");
			param.put("client_secret", jsonMap.get("client_secret") + "");
			String resData = jsonPost(HUANXIN_TOKEN, param);
			if (!"400".equals(resData)) {
				Map<String, Object> resJson = JSONUtil.fromJson(resData, new TypeReference<Map>(){});
				if (resJson == null)
					return new Message(2000, "获取环信accessToken出错");
				accessToken = Tools.getDesc(resJson.get("access_token"));
			} else {
				return new Message(2000, "获取环信accessToken出错");
			}	
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("hospital", hospital);
		map.put("access_token", accessToken);
		map.put("create_time", System.currentTimeMillis());
		map.put("expire_in", expireIn);
		map.put("status", 1);
		map.put("type", type);
		Message message = new Message(0);
		DBTools.db("basedb").addItem("access_token", map);	
		message.put("access_token", accessToken);
		return message;
	}
	
	public static Message refreshToken(Input input) {
		Integer hospital = input.getInt("hospital");
		String HUANXIN_TOKEN = "https://a1.easemob.com/" + input.getDesc("application") + "/token";
		String accessToken = input.getDesc("access_token");
		Integer type = input.getInt("type", 0); // 默认企业号
		Integer expireIn = 7000;
		Message message = new Message();
		// 数据库查询
		String hql = "from access_token where hospital = " + hospital + "  and type=" + type + " and status = " + STATUS_ENABLE + " order by create_time desc";
		List list = QBuilder.db("basedb").queryHql(hql);
		if (list.size() == 0) {
			// 没有匹配的记录
			message.setErrcode(20004);
			return message;
		}
		if (type == 2) {
			expireIn = 5180000;// 环信默认7天有效期
			List<Hospital> hList = QBuilder.db("basedb").queryHql("from Hospital where hospital=" + hospital);
			if (hList.size() == 0) {
				return new Message(1999, "没有该医院的环信账号");
			}
			Map jsonMap = hList.get(0).getJson();
			Map<String, String> param = new HashMap<String, String>();
			param.put("grant_type", jsonMap.get("grant_type") + "");
			param.put("client_id", jsonMap.get("client_id") + "");
			param.put("client_secret", jsonMap.get("client_secret") + "");
			String resData = jsonPost(HUANXIN_TOKEN, param);
			if (!"400".equals(resData)) {
				Map<String, Object> resJson = JSONUtil.fromJson(resData, new TypeReference<Map>(){});
				accessToken = Tools.getDesc(resJson.get("access_token"));
			} else {
				return new Message(2000, "获取环信accessToken出错");
			}	
		}
		// 取出数据库中token记录
		Map tokenMap = (HashMap) list.get(0);
		// 修改创建时间
		Long now = System.currentTimeMillis();
		tokenMap.put("create_time", now);
		tokenMap.put("access_token", accessToken);
		tokenMap.put("expire_in", expireIn);
		DBTools.db("basedb").modItem("access_token", tokenMap);
		message.setErrmsg("token更新成功");
		message.put("access_token", accessToken);
		message.put("expire_in", expireIn);
		return message;
	}
	
	
	// 获取环信token
	public static String jsonPost(String url, Map<String, String> jsonParam) {
		String resData = null;
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost method = new HttpPost(url);
			StringEntity entity = new StringEntity(JSONUtil.toJson(jsonParam),
					"utf-8");
			entity.setContentEncoding("UTF-8");
			entity.setContentType("application/json");
			method.setEntity(entity);
			HttpResponse result = httpClient.execute(method);
			int code = result.getStatusLine().getStatusCode();
			// 根据环信开发者文档，状态码400说明用户名密码有问题
			if (400 == code) {
				resData = "400";
			} else {
				// 请求结束，返回结果
				resData = EntityUtils.toString(result.getEntity());
			}
		} catch (Exception e) {
			resData = "500";
		}
		return resData;
	}
%>
<%
	Tools.encryptPrint(out, createToken(input));
%>